<?php
// 
defined('BY_JYA') or exit('error');

class Auction{
	 public function check($pid) {
		$isUser = pdo_count('jy_jdpm_auction',array('id'=>$pid,'mid' => $_SESSION['uid']),'id');
        $code   = (int)$isUser;
		if($isUser){
			 exi('您当前为最高出价者!','error');
		}
       
    }
	
	/**
     * 竞价
     */
    public function biding($pid) {
		cache_delete('commodity-' . $pid );
        $FirstUser = cache_read('commodity-' . $pid,'jy_jdpm');
        if (empty($FirstUser)) {
            $FirstUser[0] = array('user' => $_SESSION['uid'] , 'pid' => $pid);
            cache_write('commodity-' . $pid , $FirstUser ,'jy_jdpm');
        }else{
			if ($FirstUser[0]['user'] == $_SESSION['uid']) {
				exi('您已经在竞拍，请勿重复点击..','error');
			}
		}

        sleep(2);
		$FirstUser = cache_read('commodity-' . $pid,'jy_jdpm');
        if ($FirstUser[0]['user'] != $_SESSION['uid']) {
            exi('被人捷足先登了，稍后再拍..','error');
        }
        return $this->payDeposit($pid);
    }
	 /**
     * 验证支付密码
     */
    private function checkPaw($Paw) {
		$count = pdo_count('jy_jdpm_member',array('paypwd' => encryptPwd($Paw) , 'mid' => $_SESSION['uid']),'mid');
        return $count;
    }
	/**
     * 交保证金/跟拍/竞价
     */
    public function payDeposit($pid) {
		if (!$_SESSION['uid']) {
			cache_delete('commodity-' . $pid );
			 exi('请先登录..','error','member/login/');
        }
        //encryptPwd( $data['paypwd']) 生成密码

        //获取拍品当前拍卖价
        //$Good = $this->Goods->getInfo($this->AuctionID);
			$Good = pdo_get('jy_jdpm_auction',array('id'=>$pid));
			$info = pdo_get('jy_jdpm_goods',array('id'=>$Good['goodsid']));
			$Good['id'] = $info['id'];
			$Good['price'] = $Good['nowprice'];
			$Good['size'] = $Good['stepsize'];
			$Good['type'] = $Good['stepsize_type'];
			$Good['offer_man'] = $Good['mid'];
			$Good['insured_man'] = $Good['mid'];
			$userinfo = pdo_get('jy_jdpm_freezelog',array('pid'=>$pid,'mid'=>$Good['mid'],'status'=>0));
			$Good['offer_man'] = $userinfo['mid'];
			//获取当前最高保证金
			$Good['margin'] = $userinfo['pledge'];
        //拍卖是否进行中
        if (time() < $Good['starttime']) {
            cache_delete('commodity-' . $pid );
            exi('当前竞拍尚未开拍','error');
        }
        if (time() > $Good['endtime']) {
            cache_delete('commodity-' . $pid );
			 exi('当前竞拍已结束','error');
        }

        //判断是否为最高出价者
        if ($Good['offer_man'] == $_SESSION['uid']) {
			 cache_delete('commodity-' . $pid );
			 exi('您当前为最高出价者!','error');
        }
		//起拍比例设置
		$orderset=plugin_set('order');
		$onsetbi = $orderset['onsetbi'] ? $orderset['onsetbi'] : 3;
        //余额是否充足
        $nowMoney = $Good['offer_man'] > 0 ? ($Good['price'] + ($Good['onset'] * 0.1)) : $Good['onset'];
        $money    = ($nowMoney >= ($Good['onset'] * $onsetbi)) ? $nowMoney : (($Good['offer_man'] > 0) ? ($nowMoney / 2) : ($Good['onset'] / 2));//保证金金额
		
		//余额是否充足
        if (!$this->judgeMoney($money)) {
			 cache_delete('commodity-' . $pid );
			 exi('余额不足,是否进充值？','error','core/member.recharge/');
        }
		pdo_begin();
        try {
		   //获取处理当前拍前一位交保证金人员 更新用户表信息  保证金表
			pdo_update('jy_jdpm_freezelog',array('status' => 1, 'rtime' => time()), array('pid' => $Good['id'],'status'=>0));

            //退还上一位提交保证金用户保证金
			pdo_update('jy_jdpm_member',array('wallet_pledge_freeze -=' => $Good['margin']), array('mid' => $Good['insured_man']));

            //更新当前用户信息 添加当前用户交保证金并扣除金额
			pdo_update('jy_jdpm_member',array('wallet_pledge_freeze +=' => $money), array('mid' => $_SESSION['uid']));
			pdo_insert('jy_jdpm_freezelog',array('mid' => $_SESSION['uid'] , 'pid' => $Good['id'] , 'gid' => $Good['goodsid'] , 'pledge' => $money , 'createtime' => time(), 'status' => 0));

            //更新拍卖表信息 //当前拍卖金额
            $moneynew       = $Good['price'] ? $Good['price'] : $Good['onset'];
            $moneynew       = $moneynew + ($Good['onset'] / 10);
            $NowPrice    = $Good['offer_man'] ? $moneynew : $Good['onset'];
            $UpToAuction = ['nowprice' => $NowPrice , 'mid' => $_SESSION['uid']];

            if (time() > ($Good['endtime'] - 300)) {
                $UpToAuction['endtime'] = time() + 300;
            }

            $UpToAuction['overtime'] = 1;
			pdo_update('jy_jdpm_auction',$UpToAuction, array('id' => $Good['id']));
			pdo_update('jy_jdpm_auction',array('bidcount +=' => 1), array('id' => $Good['id']));

            //添加拍卖记录
			pdo_insert('jy_jdpm_auction_record', array('pid' => $Good['id'] ,'uniacid'=>$_SESSION['uniacid'], 'mid' => $_SESSION['uid'] , 'createtime' => time() , 'money' => $NowPrice));

            //提交记录金额记录
            $Log = array(
				'pid'         => $pid ,
                'mid'         => $_SESSION['uid'] ,
                'money'       => $money ,
                'channel'     => 2 ,
				'type'     => 1 ,
                'create_time' => time() ,
                'update_time' => time() ,
                'remarks'     => '提交保证金额！！' ,
				'uniacid'=>$_SESSION['uniacid'],
            );
			pdo_insert('jy_jdpm_money_log', $Log);
			cache_delete('commodity-' . $pid);
			//发送新用户
			$newmember = pdo_get('jy_jdpm_member',array('mid'=>$_SESSION['uid']));
			$msg =array('username'=>$newmember['nickname'],'pname'=>$Good['pname']);
			//set_sms($newmember['mobile'],$msg,1,$_SESSION['uid']);
			set_websms($newmember['nickname'].':您已成功竞拍本拍品！',0,$_SESSION['uid'],'',$pid);
			
			//退保记录金额记录
            if ($Good['offer_man']) {
                $Log = array(
					'pid'         => $pid ,
                    'mid'         => $Good['insured_man'] ,
                    'money'       => $Good['margin'] ,
					'type'     => 1 ,
                    'channel'     => 1 ,
                    'create_time' => time() ,
                    'update_time' => time() ,
                    'remarks'     => '退还保证金额-竞价' ,
					'uniacid'=>$_SESSION['uniacid'],
                );
				pdo_insert('jy_jdpm_money_log', $Log);
				//发送老用户
				cache_delete('commodity-' . $pid);
				$oldmember = pdo_get('jy_jdpm_member',array('mid'=>$Good['insured_man']));
				$msg =array('pname'=>$Good['pname']);
				//set_sms($oldmember['mobile'],$msg,2,$Good['insured_man']);
				set_websms($oldmember['nickname'].':您的竞拍《'.$Good['pname'].'》已被他人抢拍，您将获得差价利益30%的奖励，交易成功时到账！',0,$Good['insured_man'],$url='jy_jdpm/detail//id='.$pid,$pid);
            }
            cache_delete('commodity-' . $pid);
			pdo_commit();
        } catch (\Exception $E) {
			pdo_rollback();
			cache_delete('commodity-' . $pid);
			exi('竞价失败','error');
        }
		$uniacid=$_SESSION['uniacid']?$_SESSION['uniacid']:1;
		$set=plugin_set('basic');
		pdo_update('core_members',array('credit1'=>$credit1),array('id'=>$uid));
		cache_delete('commodity-' . $pid);
		set_workerman($pid);
		exi('竞价成功！','','jy_jdpm/detail//id='.$pid);
    }
	
	/**
     * 判断账户余额是否充足
     * @param int $Money
     * @return int
     */
    public function judgeMoney($Money = 0) {
//        $MemberPledgeTake  = M('MemberPledgeTake')->where(['mid' => $_SESSION['uid'] , 'status' => 0])->sum('money');
        $credit2 = pdo_getcolumn('core_members',array('id' => $_SESSION['uid']),'credit2');
		$wallet_pledge_freeze = pdo_getcolumn('jy_jdpm_member',array('mid' => $_SESSION['uid']),'wallet_pledge_freeze');
        $res = $credit2 > ($Money + $wallet_pledge_freeze) ?true:false;
		return $res;
    }
}

?>
